package com.qiantu.phone.ui.activity;

import android.content.Intent;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.base.BaseAdapter;
import com.hjq.http.listener.HttpCallback;
import com.qiantu.api.db.LLFloorDBManager;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.event.RoomIconSelectEvent;
import com.qiantu.phone.ui.fragment.RoomIconFragment;
import com.qiantu.phone.utils.Constants;
import com.qiantu.phone.event.RefreshFloorRoomEvent;
import com.qiantu.phone.ui.adapter.RoomDemoAdapter;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.qiantu.phone.widget.EditTextLayout;
import com.lxj.xpopup.XPopup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class AddRoomActivity extends AppActivity {
    private ImageView mSortFloor;
    private ImageView mAddFloor;
    private RecyclerView mFloorList;
    private List<FloorBean> floorBeans;
    private View floorListLy;
    private BottomEditDialog mBottomEditDialog;
    private BottomEditDialog mNameBottomEditDialog;
    private String roomName;
    private String roomSerialNo;
    private String floorSerialNo;
    private String floorName;
    private int type = 0;//0:add, 1:edit
    private RoomDemoAdapter mRoomDemoAdapter;
    private RecyclerView roomRecyclerView;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_room;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mSortFloor = findViewById(R.id.sort_floor);
        mAddFloor = findViewById(R.id.add_floor);
        mFloorList = findViewById(R.id.floor_list);
        floorListLy = findViewById(R.id.floor_list_ly);
        floorAdapter = new FloorAdapter();
        floorAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                floorAdapter.setSelect(position);
            }
        });
        mFloorList.setLayoutManager(new GridLayoutManager(this, 3));
        mFloorList.setAdapter(floorAdapter);
        setOnClickListener(mSortFloor,mAddFloor);
        roomSerialNo = getIntent().getStringExtra("roomSerialNo");
        floorSerialNo = getIntent().getStringExtra("floorSerialNo");
        roomName = getIntent().getStringExtra("roomName");
        floorName = getIntent().getStringExtra("floorName");
        if (TextUtils.isEmpty(roomSerialNo)) {
            setTitle(R.string.add_room);
            type = 0;
        } else {
            setTitle(R.string.edit_room);
            type = 1;
        }
    }

    @Override
    protected void initData() {
        floorBeans = getFloorData();
        //默认楼层时设置当前所选楼层floorSerialNo，但不显示,
        if (floorBeans.size() == 1 && floorBeans.get(0).getType() == 1) {
            floorSerialNo = floorBeans.get(0).getFloorSerialNo();
            mSortFloor.setVisibility(View.GONE);
//            floorListLy.setVisibility(View.GONE);
        } else {
            floorAdapter.setNewInstance(floorBeans);
            if (floorBeans == null || floorBeans.isEmpty()) {
//                floorListLy.setVisibility(View.GONE);
                mSortFloor.setVisibility(View.GONE);
            } else {
//                floorListLy.setVisibility(View.VISIBLE);
                mSortFloor.setVisibility(View.VISIBLE);
                if (TextUtils.isEmpty(floorSerialNo)) {
                    floorAdapter.setSelect(0);
                } else {
                    floorAdapter.setSelect(floorSerialNo);
                }
            }
        }
    }

    private List<FloorBean> getFloorData() {
        return LLFloorDBManager.getInstance(this).getAll();
    }

    private boolean checkSetData() {
        if (!floorAdapter.getData().isEmpty() && floorAdapter.getSelectItem() == null) {
            toast("请选择楼层");
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View view) {
        if (view == mAddFloor) {
            showBottomEditDialog("");
        }else if(view == mSortFloor){
            Intent intent = new Intent(this, FloorSortActivity.class);
            startActivity(intent);
        }
    }

    private void showBottomEditDialog(String text) {
        if (mBottomEditDialog == null) {
            mBottomEditDialog = new BottomEditDialog(this);
            mBottomEditDialog.setDialogClickListener(new BottomEditDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    creatFloor(mBottomEditDialog.getText());
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomEditDialog);
        }
        mBottomEditDialog.setLabel(getString(R.string.floor_name));
        mBottomEditDialog.setBtnText(getString(R.string.add));
        mBottomEditDialog.setText(text);
        mBottomEditDialog.setMaxLength(Constants.FLOOR_NAME_MAX_LENGTH);
        mBottomEditDialog.show();
    }

    private void creatFloor(String floorName) {
        LLHttpManager.addFloor(this, AppApplication.getInstance().getCurrentHouseSerialNo(), floorName, new HttpCallback<HttpData<FloorBean>>(this) {
            @Override
            public void onSucceed(HttpData<FloorBean> result) {
                super.onSucceed(result);
                //楼层空时,要把当前所有房间移到创建的新楼层下
                if (floorBeans == null || floorBeans.size() == 0 || (floorBeans.size() == 1 && floorBeans.get(0).getType() == 1)) {
                    floorSerialNo = result.getData().getFloorSerialNo();
                    LLRoomDBManager.getInstance(getContext()).setAllRoomFloorSerialNo(floorSerialNo, null);
                }
                setResult(RESULT_OK);
//                LLFloorDBManager.getInstance(getContext()).removeDefaultFloor();
                LLFloorDBManager.getInstance(getContext()).put(result.getData());
                initData();
                EventBus.getDefault().post(new RefreshFloorRoomEvent());
            }
        });
    }

    private void showRoomBottomEditDialog(String text,String type) {
        if (mNameBottomEditDialog == null) {
            mNameBottomEditDialog = new BottomEditDialog(this);
            mNameBottomEditDialog.setDialogClickListener(new BottomEditDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    String text = mNameBottomEditDialog.getText();
                    if(TextUtils.isEmpty(text)){
                        toast("请输入房间名称");
                        return;
                    }

                    addRoom(text,type);
                }
            });
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mNameBottomEditDialog);
        }
        mNameBottomEditDialog.setLabel(getString(R.string.room_name));
        mNameBottomEditDialog.setText(text);
        mNameBottomEditDialog.setBtnText("保存");
        mNameBottomEditDialog.setCheckEnable(false);
        mNameBottomEditDialog.setMaxLength(Constants.ROOM_NAME_MAX_LENGTH);
        mNameBottomEditDialog.show();
    }

    public void addRoom(String text, String type){
        FloorBean selectedFloor = floorAdapter.getSelectItem();
        floorSerialNo = selectedFloor == null ? floorSerialNo : selectedFloor.getFloorSerialNo();
        LLHttpManager.addRoom(this, floorSerialNo, text, type, new HttpCallback<HttpData<RoomBean>>(this) {
            @Override
            public void onSucceed(HttpData<RoomBean> result) {
                super.onSucceed(result);
                LLRoomDBManager.getInstance(getContext()).put(result.getData());
                Intent data = new Intent();
                data.putExtra("floorSerialNo", result.getData().getFloorSerialNo());
                data.putExtra("roomName", result.getData().getRoomName());
                data.putExtra("roomSerialNo", result.getData().getRoomSerialNo());
                data.putExtra("roomTypeId ",result.getData().getRoomTypeId());
                if (selectedFloor != null) {
                    data.putExtra("floorName", selectedFloor.getFloorName());
                }
                EventBus.getDefault().post(new RefreshFloorRoomEvent());
                setResult(RESULT_OK, data);
                finish();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRoomIconSelectEvent(RoomIconSelectEvent event) {
        showRoomBottomEditDialog(event.name,event.iconType);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private FloorAdapter floorAdapter;

    private class FloorAdapter extends BaseQuickAdapter<FloorBean, BaseViewHolder> {
        private FloorBean mSelectBean;

        public FloorAdapter() {
            super(R.layout.select_floor_item);
        }

        @Override
        protected void convert(BaseViewHolder helper, FloorBean item) {
            helper.setText(R.id.name, item.getFloorName());
            RadioButton checkbox = helper.getView(R.id.checkbox);
            if (mSelectBean != null && !TextUtils.isEmpty(mSelectBean.getFloorSerialNo()) && mSelectBean.getFloorSerialNo().equals(item.getFloorSerialNo())) {
                checkbox.setChecked(true);
            } else {
                checkbox.setChecked(false);
            }
        }

        public void setSelect(FloorBean bean) {
            mSelectBean = bean;
            notifyDataSetChanged();
        }

        public void setSelect(int position) {
            if (position < getData().size()) {
                mSelectBean = getData().get(position);
                notifyDataSetChanged();
            }
        }

        public void setSelect(String floorSerialNo) {
            for (FloorBean bean : getData()) {
                if (!TextUtils.isEmpty(floorSerialNo) && floorSerialNo.equals(bean.getFloorSerialNo())) {
                    mSelectBean = bean;
                }
            }
            notifyDataSetChanged();
        }

        public FloorBean getSelectItem() {
            return mSelectBean;
        }
    }
}